﻿using MediatR;
using Microsoft.AspNetCore.Mvc;
using Order.Api.Write.Application.Command;
using Order.ErrorCode;
using System;
using System.Threading.Tasks;

namespace Order.Api.Write.Controllers
{
    /// <summary>
    /// 退款控制器
    /// 提供退款状态更新相关的API接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class RefundController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者模式处理器</param>
        public RefundController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator), "中介者处理器不能为空");
        }

        /// <summary>
        /// 更新退款状态
        /// 支持所有状态变更操作：审批、拒绝、处理等
        /// </summary>
        /// <param name="request">退款状态更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPost("update-status")]
        public async Task<ApiResult<int>> UpdateRefundStatus([FromBody] RefundStatusUpdateCommand request)
        {
            try
            {
                // 参数验证
                if (request == null)
                {
                    return new ApiResult<int> { Code = ApiEnums.Fail, Msg = "状态更新请求不能为空" };
                }

                if (request.RefundId <= 0)
                {
                    return new ApiResult<int> { Code = ApiEnums.Fail, Msg = "退款ID必须大于0" };
                }

                // 发送命令并获取结果
                var result = await _mediator.Send(request);

                if (result)
                {
                    return new ApiResult<int> { Code = ApiEnums.Success, Data = request.RefundId, Msg = "退款状态更新成功" };
                }
                else
                {
                    return new ApiResult<int> { Code = ApiEnums.Fail, Msg = "退款状态更新失败" };
                }
            }
            catch (ArgumentException ex)
            {
                // 参数错误或记录不存在
                return new ApiResult<int> { Code = ApiEnums.NotFound, Msg = ex.Message };
            }
            catch (InvalidOperationException ex)
            {
                // 状态不允许操作
                return new ApiResult<int> { Code = ApiEnums.Fail, Msg = ex.Message };
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: 添加日志记录
                return new ApiResult<int> { Code = ApiEnums.Error, Msg = $"更新退款状态时发生错误: {ex.Message}" };
            }
        }
    }
}
